package com.zzq.consumer.rule;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @Author zzq
 * @Date 2020/3/8 21:36
 * @Version 1.0
 */
public class MyRule implements IRule {
    private ILoadBalancer loadBalancer;
    //需要排除的端口
    List<Integer> ports;

    public MyRule(){
    }

    public MyRule(List<Integer> ports) {
        this.ports= Arrays.asList(1,2,3,4,5);
    }

    @Override
    public Server choose(Object key) {
        //获取所有provider
        List<Server> allServers = loadBalancer.getAllServers();
        //获取所有可用的provider
        List<Server> availableServers = this.getAvailableServers(allServers);
        return getRandomServers(availableServers);
    }

    private List<Server> getAvailableServers(List<Server> servers) {
        List<Server> collect = servers.stream().filter(server -> !ports.contains(server.getPort())).collect(Collectors.toList());
        return collect;
    }

    private Server getRandomServers(List<Server> servers) {
        Random random = new Random();
        int i=servers.size();
        return servers.get(random.nextInt(i));
    }

    @Override
    public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
        this.loadBalancer=iLoadBalancer;
    }

    @Override
    public ILoadBalancer getLoadBalancer() {
        return loadBalancer;
    }
}
